package com.application.api;

import com.application.api.entity.ResultEntity;
import com.application.model.UserPoint;
import com.application.module.userinfo.Userinfo;
import com.application.service.UserService;
import com.application.vo.UserVo;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.platform.annotation.Controller;
import com.platform.constant.ConstantWebContext;
import com.platform.interceptor.AuthInterceptor;
import com.platform.interceptor.LoginInterceptor;
import com.platform.interceptor.ParamPkgInterceptor;
import com.platform.mvc.base.BaseController;
import com.platform.mvc.login.LoginValidator;
import com.platform.mvc.operator.Operator;
import com.platform.mvc.user.User;
import com.platform.mvc.user.UserValidator;
import com.platform.tools.ToolWeb;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpStatus;

/**
 * 登陆注销
 */
@Controller("/api/login")
@Clear({LoginInterceptor.class, AuthInterceptor.class, ParamPkgInterceptor.class})
public class LoginApiController extends BaseController {

    public static String prefix = "/upload/user/";
    UserService userService;

    /**
     * @param username|用户名|String|必填
     * @param password|密码|String|可选
     * @param valicode
     * @title 登陆验证
     */
    @Before(LoginValidator.class)
    public void index() {
        User user = getAttr("user");
        String iid = getPara("inviteId");
        if(iid != null && !iid.equalsIgnoreCase(user.getId().toString())){
            if(user.getRefereeUserid() == null) {
                user.set("referee_userid", iid).update();
            }
        }
        User.updateInfo(user);
        success(getLoginResult(user), "Ok");
    }

    private UserVo getLoginResult(User user) {
        AuthInterceptor.setCurrentUser(getRequest(), getResponse(), user, false);
        //pay_pass支付密码加密处理
        String payPassStr = user.getStr("pay_pass");
        String pay_pass = StrKit.isBlank(payPassStr) ? null : DigestUtils.md5Hex(payPassStr).toUpperCase();
        user.set("pay_pass", pay_pass);
        Operator operator = Operator.cacheGet("/api/stats/product");
        int stats = (operator != null && AuthInterceptor.hasPrivilegeUrl(operator.getIds(), user.getId().toString()))
                ? 1 : 0;
        //返回用户是否已签到
        UserPoint point = UserPoint.dao.loginCheck(user.getId());
        //处理用户余额money=money+gift
        user.set("money", user.getBigDecimal("money").add(user.getBigDecimal("gift")));
        user.put("info", Userinfo.dao.findInfo(user.getId()));
        user.put("is_vip", User.isVip(user));

        return new UserVo(getAttr("authmark"), user, stats, point == null ? 0 : 1);
    }


    /**
     * @title 注销登陆
     * @respBody {
     * "code": 200,
     * "data": null,
     * "description": "成功退出登录！"
     * }
     */
    public void logout() {
        ToolWeb.addCookie(getRequest(), getResponse(), "", null, true, ConstantWebContext.cookie_authmark, null, 0);

        renderJson(new ResultEntity(HttpStatus.SC_OK, "成功退出登录！"));
    }


    /*
    如果发现已经有此账号 就返回用户信息
    参数：openid和open_type
     */
    @Before(LoginValidator.class)
    public void open(){
        User user = getAttr("user");
        if(user == null ){
            error(404, "用户不存在");
            return;
        }
        User.updateInfo(user);
        success(getLoginResult(user), "Ok");
    }


    /**
     * 第三方登录后绑定微信号与手机,用于第一次第三方登录时绑定手机号(下载头像地址,并存储在本地)
     * @param mobile 手机号
     * @param valicode 验证码
     * @param openid
     * @param nickname 昵称
     * @param img 头像url
     */
    @Before({UserValidator.class, Tx.class})
    public void bind(){
        String mobile = getPara("mobile");
        String openid = getPara("openid");
        String openType = getPara("openType", "wx");
        String name = getPara("nickname");
        String img = getPara("img");

        User user = User.dao.findByOpenid(openid);
        if(user == null){
            user = new UserService().registerUser(mobile, openid, openType, name, img);
            String iid = getPara("inviteId");
            if(iid != null && !"null".equalsIgnoreCase(iid) && !iid.equalsIgnoreCase(user.getId().toString())){
                if(user.getRefereeUserid() == null && User.dao.findById(iid) != null) {
                    user.set("referee_userid", iid).update();
                }
            }
        } else {
            if(StrKit.notBlank(mobile)) {
                user.set("mobile", mobile).setUsername(mobile);
                user.update();
            }
        }
        AuthInterceptor.setCurrentUser(getRequest(), getResponse(), user, false);
        success(getLoginResult(user));
    }

    /*
    刷新token
     */
    @Before(LoginInterceptor.class)
    public void refresh(){
//        User user = AuthInterceptor.getCurrentUser(getRequest(), getResponse(), false);
        User user = User.dao.findById(getPara("id"));
        if(user == null){
            error(401, "请先登陆");
            return;
        }
        success(getLoginResult(user));
    }
}
